package com.project.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.project.bean.RoleBean;
import com.project.mapper.IGradeMapper;
import com.project.mapper.IRoleMapper;
import com.project.service.IRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional
public class RoleServiceImpl implements IRoleService {
    @Autowired
    private IRoleMapper roleMapper;
    @Autowired
    private IGradeMapper gradeMapper;
    @Override
    public List<RoleBean> findAllRole() {
        return roleMapper.selectList(null);
    }

    @Override
    public IPage<RoleBean> findByItem(Integer pageNO) {
        return roleMapper.selectPage(new Page<>(pageNO,3),null);
    }

    @Override
    public boolean add(String roleName, Integer[] gradeIdArray) {
        QueryWrapper<RoleBean> qw = new QueryWrapper<>();
        qw.eq("r_name",roleName);
        if (roleMapper.selectCount(qw) == 0){
            RoleBean role =new RoleBean(roleName);
            roleMapper.insert(role);
            roleMapper.addGrade(role.getRoleId(),gradeIdArray);
            return true;
        }
        return false;
    }

    @Override
    public void del(Integer roleId) {
        //删角色
        roleMapper.deleteById(roleId);
        //删角色用户中间表
        roleMapper.delRoleUser(roleId);
        //删角色权限中间表
        roleMapper.delRoleGrade(roleId);
    }

    @Override
    public RoleBean findById(Integer roleId) {
        RoleBean roleBean =roleMapper.selectById(roleId);
        roleBean.setGradeList(gradeMapper.findByRoleId(roleId));
        return roleBean;
    }

    @Override
    public void update(Integer roleId, Integer[] gradeIdArray) {
        //先删除
        roleMapper.delRoleGrade(roleId);
        //再修改
        roleMapper.addGrade(roleId,gradeIdArray);
    }
}
